import { create } from 'zustand';
import { iconMapping } from '../utils';

const useTerminalStore = create((set, get) => ({
  // 创建新的输出行对象
  createLine: (content, type = 'normal', extraProps = {}) => {
    return {
      id: crypto.randomUUID(),
      content,
      type,
      timestamp: new Date().toISOString(),
      ...extraProps
    };
  },
  // 终端输出状态 - 改为数组形式，每行一个对象
  outputLines: [],
  
  // 终端可见性状态
  isVisible: false, // 默认隐藏
  
  // 输出配置
  outputConfig: {
    maxLines: 1000,       // 最大行数
    trimToLines: 500,     // 修剪到行数
    autoScroll: true,     // 自动滚动到底部
    showTimestamp: true,  // 显示时间戳
  },
  
  // 输出历史
  outputHistory: [],
  
  // Actions
  
  // 切换终端可见性
  toggleVisibility: () => {
    set((state) => ({ isVisible: !state.isVisible }));
  },
  
  // 显示终端
  showTerminal: () => {
    set({ isVisible: true });
  },
  
  // 隐藏终端
  hideTerminal: () => {
    set({ isVisible: false });
  },
  
  // 添加输出内容 - 支持单行或多行
  addOutput: (text) => {
    if (text === '') {
      set({ outputLines: [] });
      return;
    }
    
    // 当有新输出时自动显示终端
    set((state) => {
      // 将文本按行分割
      const lines = text.split('\n');
      const newLines = lines.map((line) => get().createLine(line, 'normal'));
      
      const updatedLines = [...state.outputLines, ...newLines];
      const trimmedLines = get().trimOutputLines(updatedLines);
      
      return { 
        outputLines: trimmedLines,
        isVisible: true // 自动显示终端
      };
    });
  },
  
  // 添加单行输出
  addOutputLine: (line, type = 'normal') => {
    set((state) => {
      const newLine = get().createLine(line, type);
      const updatedLines = [...state.outputLines, newLine];
      const trimmedLines = get().trimOutputLines(updatedLines);
      
      return { 
        outputLines: trimmedLines,
        isVisible: true
      };
    });
  },
  
  // 添加错误行
  addErrorLine: (line, errorInfo = {}) => {
    set((state) => {
      const newLine = get().createLine(line, 'error', { errorInfo });
      const updatedLines = [...state.outputLines, newLine];
      const trimmedLines = get().trimOutputLines(updatedLines);
      
      return { 
        outputLines: trimmedLines,
        isVisible: true
      };
    });
  },
  
  // 添加警告行
  addWarningLine: (line) => {
    set((state) => {
      const newLine = get().createLine(line, 'warning');
      const updatedLines = [...state.outputLines, newLine];
      const trimmedLines = get().trimOutputLines(updatedLines);
      
      return { 
        outputLines: trimmedLines,
        isVisible: true
      };
    });
  },
  
  // 添加系统消息行
  addSystemLine: (line, iconType = iconMapping.SYSTEM_ICONS.SYSTEM_INFO, title = '系统消息', duration = '', timestamp = '') => {
    set((state) => {
      const newLine = get().createLine(line, 'system', {
        iconType,
        title,
        duration,
        timestamp,
        timestampISO: new Date().toISOString()
      });
      
      const updatedLines = [...state.outputLines, newLine];
      const trimmedLines = get().trimOutputLines(updatedLines);
      
      return { 
        outputLines: trimmedLines,
        isVisible: true
      };
    });
  },
  
  // 清空输出
  clearOutput: () => {
    set({ outputLines: [] });
  },
  
  // 修剪输出行数
  trimOutputLines: (lines) => {
    const { outputConfig } = get();
    if (lines.length > outputConfig.maxLines) {
      const trimmed = lines.slice(-outputConfig.trimToLines);
      // 在开头添加一个省略行
      return [
        get().createLine('...', 'system', {
          iconType: iconMapping.SYSTEM_ICONS.SYSTEM_INFO,
          title: '输出已截断'
        }), 
        ...trimmed
      ];
    }
    return lines;
  },
  
  // 获取当前输出文本（用于兼容性）
  getOutputText: () => {
    const { outputLines } = get();
    return outputLines.map(line => line.content).join('\n');
  },
  
  // 解析输出内容（简化版本，移除 emoji 解析）
  parseOutput: (text) => {
    if (!text) return [];
    
    const parts = [];
    
    // 收集所有匹配项，按位置排序
    const allMatches = [];
    
    // 添加错误匹配
    const errorRegex = /##ERROR_START##(.*?)##ERROR_END##/gs;
    let match;
    while ((match = errorRegex.exec(text)) !== null) {
      allMatches.push({
        type: 'error',
        start: match.index,
        end: errorRegex.lastIndex,
        content: match[1]
      });
    }
    
    // 添加警告匹配
    const warningRegex = /##WARNING_START##(.*?)##WARNING_END##/gs;
    while ((match = warningRegex.exec(text)) !== null) {
      allMatches.push({
        type: 'warning',
        start: match.index,
        end: warningRegex.lastIndex,
        content: match[1]
      });
    }
    
    // 添加系统消息匹配
    const systemRegex = /##SYSTEM_START##(.*?)##SYSTEM_END##/gs;
    while ((match = systemRegex.exec(text)) !== null) {
      allMatches.push({
        type: 'system',
        start: match.index,
        end: systemRegex.lastIndex,
        content: match[1]
      });
    }
    
    // 按开始位置排序
    allMatches.sort((a, b) => a.start - b.start);
    
    let lastIndex = 0;
    
    // 处理所有匹配项
    allMatches.forEach(item => {
      // 添加之前的普通文本
      if (item.start > lastIndex) {
        const normalText = text.substring(lastIndex, item.start);
        if (normalText.trim()) {
          parts.push({ type: 'normal', content: normalText });
        }
      }
      
      if (item.type === 'error') {
        const lines = item.content.split('\n').filter(line => line.trim());
        let errorInfo = {};
        
        lines.forEach(line => {
          if (line.includes('行 ')) {
            // 匹配新格式: 行 ##LINE##1##LINE## : ##MESSAGE##错误信息##MESSAGE##
            const lineMatch = line.match(/行 ##LINE##(\d+)##LINE##/);
            const colMatch = line.match(/列 ##COLUMN##(\d+)##COLUMN##/);
            const messageMatch = line.match(/##MESSAGE##(.*)##MESSAGE##/);
            
            if (lineMatch) errorInfo.line = parseInt(lineMatch[1]);
            if (colMatch) errorInfo.column = parseInt(colMatch[1]);
            if (messageMatch) errorInfo.message = messageMatch[1].trim();
          }
        });
        
        parts.push({ type: 'error', content: item.content, errorInfo });
      } else if (item.type === 'warning') {
        parts.push({ type: 'warning', content: item.content });
      } else if (item.type === 'system') {
        const systemContent = item.content;
        
        // 解析系统消息格式: title │ duration │ timestamp
        const parts_system = systemContent.split('│').map(p => p.trim());
        const title = parts_system[0] || '系统消息';
        
        // 解析时间信息
        let timestamp = '', duration = '';
        
        for (let i = 1; i < parts_system.length; i++) {
          const part = parts_system[i];
          if (part.includes('⏱️') || part.includes('耗时') || part.includes('duration')) {
            duration = part.replace(/⏱️|耗时|duration/gi, '').trim();
          } else if (part.includes('🕐') || part.includes('时间') || part.includes('time')) {
            timestamp = part.replace(/🕐|时间|time/gi, '').trim();
          }
        }
        
        parts.push({ 
          type: 'system', 
          iconType: iconMapping.SYSTEM_ICONS.SYSTEM_INFO, 
          title, 
          message: title, 
          timestamp, 
          duration
        });
      }
      
      lastIndex = item.end;
    });
    
    // 处理剩余的普通文本
    if (lastIndex < text.length) {
      const remainingText = text.substring(lastIndex);
      if (remainingText.trim()) {
        parts.push({ type: 'normal', content: remainingText });
      }
    }
    
    return parts;
  },
  
  // 更新输出配置
  updateOutputConfig: (newConfig) => {
    set((state) => ({
      outputConfig: { ...state.outputConfig, ...newConfig }
    }));
  },
  
  // 保存输出到历史
  saveToHistory: (label = '') => {
    const { outputLines } = get();
    if (outputLines.length > 0) {
      set((state) => ({
        outputHistory: [
          ...state.outputHistory.slice(-9), // 保留最近10个记录
          {
            id: Date.now(),
            label: label || `输出 ${new Date().toLocaleTimeString()}`,
            content: outputLines,
            timestamp: new Date(),
          }
        ]
      }));
    }
  },
  
  // 清空输出历史
  clearHistory: () => {
    set({ outputHistory: [] });
  },
  
  // 从历史恢复输出
  restoreFromHistory: (id) => {
    const { outputHistory } = get();
    const historyItem = outputHistory.find(item => item.id === id);
    if (historyItem) {
      set({ outputLines: historyItem.content });
    }
  },
}));

export default useTerminalStore;
